<?php

namespace catchAdmin\externalGoods\service;

use catchAdmin\api\model\Order;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\externalGoods\model\GoodsRule as externalGoodsRuleModel;
use catchAdmin\externalGoods\model\GoodsAttribute as externalGoodsAttribute;
use catchAdmin\externalGoods\model\OrderLogistics;
use catchAdmin\product\model\GoodsDescription;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Goods;
use houniao\api\v1\Order as OrderApi;
use catchAdmin\externalGoods\model\OrderLogisticsTrack as LogisticsModel;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class OrderLogisticsTrackService{

    protected $user;

    public function __construct()
    {

    }

    //物流通知
    public function notifyTrack($param){
        //查询物流轨迹
        $logisticsApi = new OrderApi();
        $apiData = $logisticsApi->logistics(['order_no'=>$param['order_no']])['data'];

        if(empty($apiData)){
            return false;
        }

        $logisticsModel = new LogisticsModel;

        $insert = [];

//        $apiData = [
//            [
//                "express_no"=> "qwe123123", //快递编号
//            "express_code"=> "EMS", //快递Code
//            "express_remark"=> "", //快递备注
//            "content"=>"[{\"Action\":\"1\",\"AcceptStation\":\"【潮州市】广东潮州市公司-林洪耿（0768-3275198|0768-2337000） 已揽收\",\"AcceptTime\":\"2022-04-22 20:06:48\",\"Remark\":\"\",\"Location\":\"潮州市\"},{\"Action\":\"2\",\"AcceptStation\":\"【潮州市】已离开 广东潮州市公司；发往 湖北武汉地区包\",\"AcceptTime\":\"2022-04-22 20:12:48\",\"Remark\":\"\",\"Location\":\"潮州市\"},{\"Action\":\"2\",\"AcceptStation\":\"【揭阳市】已到达 广东揭阳分拨交付中心\",\"AcceptTime\":\"2022-04-22 21:34:02\",\"Remark\":\"\",\"Location\":\"揭阳市\"},{\"Action\":\"2\",\"AcceptStation\":\"【揭阳市】已离开 广东揭阳分拨交付中心；发往 湖北武汉分拨交付中心\",\"AcceptTime\":\"2022-04-22 21:36:22\",\"Remark\":\"\",\"Location\":\"揭阳市\"},{\"Action\":\"2\",\"AcceptStation\":\"已到达 湖北武汉分拨交付中心\",\"AcceptTime\":\"2022-04-23 20:22:37\",\"Remark\":\"\",\"Location\":\"武汉市\"},{\"Action\":\"2\",\"AcceptStation\":\"已离开 湖北武汉分拨交付中心；发往 湖北武汉三角湖公司\",\"AcceptTime\":\"2022-04-23 20:49:26\",\"Remark\":\"\",\"Location\":\"武汉市\"},{\"Action\":\"2\",\"AcceptStation\":\"已到达 湖北武汉三角湖公司[027-59621483]\",\"AcceptTime\":\"2022-04-24 08:27:58\",\"Remark\":\"\",\"Location\":\"武汉市\"}]", //物流信息
//            "express_name"=> "EMS" //快递名称
//            ]
//        ];

        foreach ($apiData as $value){
            //拿到物流单号数量
            $count = $logisticsModel->where('express_no',$value['express_no'])->count();
            $content = json_decode($value['content'],true);
            if($count >= count($content)){//如果数量一致
                continue;
            }
            $start = -1 * (count($content) - $count);
            $newArr = array_slice($content,$start);
            foreach ($newArr as $v){
                $insert[] = [
                    'order_no'=>$param['order_no'],
                    'express_no'=>$value['express_no'],
                    'express_code'=>$value['express_code'],
                    'express_name'=>$value['express_name'],
                    'action'=>$v['Action'],
                    'accept_station'=>$v['AcceptStation'],
                    'accept_time'=>$v['AcceptTime'],
                    'remark'=>$v['Remark'],
                    'location'=>$v['Location'],
                    'supplier_id'=>1//候鸟
                ];
            }
        }

        Db::startTrans();
        try {
            //添加物流轨迹
            $logisticsModel->saveAll($insert);

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            return false;
        }
    }

    //发货通知
    public function notifySend($param){
        $order_id = $param['source_order_no'];
        $order_no = $param['order_no'];
        $express = $param['express'];

        $insert = [];
        $logistics = new OrderLogistics;

        $explode = explode('_', $order_id);
        $main_order_id = $explode[0];//主订单的ID

        if(count($explode) == 3){
            $main_order_id = $explode[0].'_'.$explode[1];
        }

        //处理物流
        foreach ($express as $value){
            $insert[] = [
                'order_id'=>$order_id,
                'main_order_id'=>$main_order_id,
                'order_no'=>$order_no,
                'express_no'=>$value['express_no'],
                'express_name'=>$value['express_name'],
                'express_code'=>$value['express_code'],
                'delivery_time'=>date('Y-m-d H:i:s',$value['delivery_time']),
                'supplier_id'=>1,
            ];
        }
        //处理商品 。。。

        Db::startTrans();
        try {

            $orderModel = (new Order)->where('orderId',$main_order_id)->find();
            $orderModel->push_status = '已发货';
            $orderModel->save();

            //添加物流轨迹
//            Log::write(json_encode($insert));
            $logistics->saveAll($insert);

            Db::commit();
            return true;
        } catch (\Exception $exception) {
//            throw new Exception($exception->getMessage());
            Db::rollback();
            return false;
        }
    }
}